package impl

import (
	"context"
	"fmt"

	"gitee.com/go-course/go11/devcloud-mini/mcenter/apps/role"
	"github.com/infraboard/mcube/pb/resource"
	"go.mongodb.org/mongo-driver/bson"
)

// 创建角色
func (i *impl) CreateRole(ctx context.Context, in *role.RoleSpec) (
	*role.Role, error) {
	ins := role.NewRole(in)
	_, err := i.col.InsertOne(ctx, ins)
	if err != nil {
		return nil, err
	}

	return ins, nil
}

// 查询角色列表
func (i *impl) QueryRole(ctx context.Context, in *role.QueryRoleRequest) (
	*role.RoleSet, error) {

	filter := bson.M{}
	if len(in.RoleIds) > 0 {
		filter["_id"] = bson.M{"$in": in.RoleIds}
	}

	fmt.Println(filter)

	res, err := i.col.Find(ctx, filter)
	if err != nil {
		return nil, err
	}

	set := &role.RoleSet{}
	for res.Next(ctx) {
		ins := &role.Role{Meta: &resource.Meta{}, Spec: &role.RoleSpec{}}
		err := res.Decode(ins)
		if err != nil {
			return nil, err
		}
		set.Items = append(set.Items, ins)
	}
	return set, nil
}
